package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelLogger"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"go-fox-edge-channel-mqtt-lora/channelEntity"
	"go-fox-edge-channel-mqtt-lora/mqtt2lora"
	"reflect"
)

type executeService struct {
}

func (e *executeService) execute(requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	if requestVO.Send == nil || requestVO.Send == "" {
		return nil, errors.New("发送数据不能为空！")
	}
	if requestVO.Timeout == 0 {
		return nil, errors.New("超时参数不能为空！")
	}

	// 获得连接
	val, ok := service.channelName2Entity.Load(requestVO.Name)
	if !ok {
		return nil, errors.New("找不到对应的通道实体:" + requestVO.Name)
	}
	loraWanEntity := val.(*channelEntity.LoraWanEntity)

	// 检查：参数是否合法
	if requestVO.Send == nil || reflect.TypeOf(requestVO.Send).Kind() != reflect.String {
		return nil, errors.New("命令参数格式必须为Hex格式的字符串:" + requestVO.Name)
	}

	send := requestVO.Send.(string)

	// 打印日志
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "发送数据", requestVO.Send)

	// 更新发送报文状态
	channelStatus.Traffic.ActiveTrafficDownloadPack(requestVO.Name)

	// 执行操作
	respond, err := mqtt2lora.Client.Request(loraWanEntity.DevEUI, loraWanEntity.FPort, send, requestVO.Timeout)
	if err != nil {
		return nil, err
	}

	// 更新接收报文状态
	channelStatus.Traffic.ActiveTrafficUploadPack(requestVO.Name)

	respondVO := commRedisRpc.Type.ChannelRespondVO.Ok(requestVO)
	respondVO.Recv = respond
	return respondVO, nil
}
